<template>
  <div class="store">
    <c-alert title="Vuex 状态"></c-alert>
    <h2>index 模块：</h2>
    <p class="mt-10">count: {{ count }}</p>
    <p class="mt-10">doubleCount: {{ doubleCount }}</p>
    <el-button class="mt-10" @click="ASYNC_FUN">Actions - ASYNC_FUN</el-button>
    <el-button class="mt-10" @click="CHANGE_COUNT(2)">Mutations - CHANGE_COUNT</el-button>

    <h2 class="mt-10">user 模块：</h2>
    <p class="mt-10">name: {{ name }}</p>
    <p class="mt-10">age: {{ age }}</p>
    <p class="mt-10">userInfo: {{ userInfo }}</p>
    <p class="mt-10">fetchSet: {{ fetchSet }}</p>
    <el-button class="mt-10" @click="CHANGE_INFO({ name: '小红', age: '16' })">Actions - CHANGE_INFO</el-button>
    <el-button class="mt-10" @click="CHANGE_NAME('小李')">Mutations - CHANGE_NAME</el-button>
    <el-button class="mt-10" @click="CHANGE_AGE('20')">Mutations - CHANGE_AGE</el-button>
    <h2 class="mt-10">数据持久化 & token 校验：</h2>
    <p class="mt-10">token: {{ token }}</p>
    <el-button class="mt-10" @click="login">登录</el-button>
    <el-button class="mt-10" @click="logout">登出</el-button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'Vuex'
export default {
  fetch({ store }) {
    store.commit('user/SET_FETCH', '通过 fetch 钩子设置的值')
  },
  computed: {
    ...mapState(['count']),
    ...mapState('user', ['name', 'age', 'fetchSet', 'token']),
    ...mapGetters(['doubleCount']),
    ...mapGetters('user', ['userInfo']),
  },
  methods: {
    ...mapActions(['ASYNC_FUN']),
    ...mapActions('user', ['CHANGE_INFO']),
    ...mapMutations(['CHANGE_COUNT']),
    ...mapMutations('user', ['CHANGE_NAME', 'CHANGE_AGE']),

    login() {
      // 当登录数据返回后设置数据持久化
      // 设置 cookie 与 vuex 的数据同步
      this.$cookies.set('token', 'token-0000-0000-0000')
      this.$store.commit('user/SET_TOKEN', 'token-0000-0000-0000')
      // 同样可以在这里做 token 的校验
      // 路由的跳转这里可以使用 this.$router.replace() 来跳转
    },
    logout() {
      this.$cookies.remove('token')
      this.$store.commit('user/SET_TOKEN', '')
    }
  },
}
</script>

<style scoped></style>